const crypto = require('node:crypto')
const fs = require("node:fs")
const path = require('path')


const getPublicKey = () => {
    return fs.readFileSync(path.resolve(process.cwd(), "key", "public_key.pem"), {
        encoding: "utf-8"
    });
}
const getPrivate = () => {
    return fs.readFileSync(path.resolve(process.cwd(), "key", "private_key.pem"), {
        encoding: "utf-8"
    });
}

const decrypt = (data) => {
    const privatekey = getPrivate();
    return crypto.privateDecrypt({ key: privatekey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING }, Buffer.from(data, 'base64')).toString('utf-8');
}

// 生成密钥对
function generateKeyPair() {
    return new Promise((resolve, reject) => {
        const options = {
            modulusLength: 2048,
            publicKeyEncoding: {
                type: 'spki',
                format: 'pem'
            },
            privateKeyEncoding: {
                type: 'pkcs8',
                format: 'pem'
            }
        };

        crypto.generateKeyPair('rsa', options, (err, publicKey, privateKey) => {
            if (err) {
                reject(err);
            } else {
                resolve({ publicKey, privateKey });
            }
        });
    });
}

// 保存密钥到文件
async function saveKeyPair() {
    try {
        const { publicKey, privateKey } = await generateKeyPair();
        fs.writeFileSync('key/public_key.pem', publicKey);
        fs.writeFileSync('key/private_key.pem', privateKey);
        console.log('公钥和私钥已生成并保存到文件中');
    } catch (err) {
        console.error('生成密钥对时出错:', err);
    }
}

module.exports = {
    decrypt,
    getPrivate,
    getPublicKey,
    saveKeyPair
}